package com.nx.platform.es.bean.modle.score;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.nx.platform.es.common.utils.MoreMaps;
import org.elasticsearch.common.unit.DistanceUnit;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author
 * @since 2016年10月17日
 */
public class GeoDistanceFilterParser implements ScoreFunctionFieldConfigParser {

    private static final Pattern FORMAT = Pattern.compile("^(\\d++(?:\\.\\d++)?+)(\\w++)?+$");

    private static double parse(String value, String unit) {
        if (value == null) {
            return 0d;
        }
        return DistanceUnit.METERS.convert(Double.parseDouble(value),
                DistanceUnit.parseUnit(unit, DistanceUnit.KILOMETERS));
    }

    @Override
    public ImmutableMap<String, ?> parse(Map<?, ?> settings) {
        String fieldName = MoreMaps.getString(settings, "fieldName");
        Preconditions.checkState(!Strings.isNullOrEmpty(fieldName), "param fieldName not found");
        double distance = 0d;
        String distanceStr = MoreMaps.getString(settings, "distance");
        if (!Strings.isNullOrEmpty(distanceStr)) {
            Matcher distanceMatcher = FORMAT.matcher(distanceStr);
            if (distanceMatcher.find()) {
                distance = parse(distanceMatcher.group(1), distanceMatcher.group(2));
            }
        }
        Preconditions.checkState(distance > 0, "distance <= 0");
        float weight = MoreMaps.getFloatValue(settings, "weight", 0f);
        ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
        builder.put("fieldName", fieldName);
        builder.put("weight", weight);
        builder.put("distance", distance);
        return builder.build();
    }

}
